import asyncio
import asyncpg
import logging

logger = logging.getLogger("pgtool")

async def create_pgpool_async(
    dsn: str,
    # min_size: int = 2,
    # max_size: int = 10,
    max_retries: int = 5,
    base_delay: float = 1.0,
    **kwargs,  # 👈 新增：接收任意额外关键字参数
) -> asyncpg.Pool:
    """
    带指数退避重试的连接池创建

    Args:
        dsn: 数据库连接字符串
        min_size: 连接池最小连接数
        max_size: 连接池最大连接数
        max_retries: 数据库连接失败时最大重试次数
        base_delay: 指数退避的初始延迟时间（数据库连接重试间隔时间）
        **kwargs: 透传给 asyncpg.create_pool() 的其他参数，
                  如 command_timeout, timeout, server_settings 等

    Returns:
        asyncpg.Pool: 成功创建的数据库连接池

    Raises:
        Exception: 经过 max_retries 次重试后仍无法连接数据库
    """
    for attempt in range(1, max_retries + 1):
        try:
            pool = await asyncpg.create_pool(
                dsn,
                # min_size=min_size,
                # max_size=max_size,
                **kwargs,  # 👈 透传所有额外参数
            )
            logger.info("✅ 数据库连接池创建成功")
            return pool
        except (OSError, asyncpg.CannotConnectNowError, asyncpg.PostgresConnectionError) as e:
            delay = base_delay * (2 ** (attempt - 1))  # 指数退避：1s, 2s, 4s, 8s...
            logger.warning(f"⚠️ 连接数据库失败 (尝试 {attempt}/{max_retries}): {e}. {delay}s 后重试...")
            if attempt == max_retries:
                raise Exception(f"❌ 经过 {max_retries} 次重试后仍无法连接数据库") from e
            await asyncio.sleep(delay)